package com.vhall.component.plugin.common.utils.algorithm;

import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.framework.common.utils.StringUtils;
import com.vhall.component.plugin.common.exception.BizErrorCode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 签名算法管理器
 *
 * @author yuanzh
 * @date 2021/9/8
 */
public class SignAlgorithmManager {

    public static final String MD5_SIGN_TYPE = "MD5";
    public static final String SHA256_SIGN_TYPE = "SHA-256";

    private SignAlgorithmManager() {
    }

    public static ISignGenerator getByName(String signType) throws BusinessException {
        if (MD5_SIGN_TYPE.equals(signType)) {
            return new Md5SignGenerator();
        }
        if (SHA256_SIGN_TYPE.equals(signType)) {
            return new Sha256SignGenerator();
        }
        throw new BusinessException(BizErrorCode.AUTH_LOGIN_SIGN_FAIL);
    }

    /**
     * 生成签名数据
     *
     * @param params 参数，参数务必去除签名
     * @return 签名数据
     */
    public static String getSignContent(Map<String, String> params) {
        StringBuilder content = new StringBuilder();
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);
        for (String key : keys) {
            String value = params.get(key).trim();
            if (StringUtils.isNotEmpty(key)) {
                content.append(key.trim());
            }
            if (StringUtils.isNotEmpty(value)) {
                content.append(value);
            }
        }
        return content.toString();
    }
}
